<template>

    <div class="con">
      <div class="left">

          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="drawpanel" name="first">
                <CanvaBoard />
            </el-tab-pane>
            <el-tab-pane label="filepanel" name="second">

               <div style="display:flex;">
                    <div v-for="item in lessionfiledata.list" style="margin-right:10px;">
                        <el-button @click="reseturl(item.filepath)">{{item.name}}</el-button>
                    </div>
                </div>


                <iframe :src="lessiondata.urlSrc" width="100%" height="600" style="border: none;margin-top:10px;"> </iframe>
            </el-tab-pane>
            <el-tab-pane label="videopanel" name="three">
              <video id="localVideo" width="100%" height="400px" autoplay="autoplay" style="border:1px solid #000000"></video>
            </el-tab-pane>
        </el-tabs>

      </div>
      <div class="right">

        <div class="content-panel" style="padding-bottom:5px;">
            <div class="content">
                <h4>Living</h4>
            </div>
            <div class="button" v-if="lessiondata.isMyCourse">

    <!-- <input type="text" id="speechInput" /> -->

        <!-- <button @click="startSpeechRecognition" >开始识别</button>
                <button @click="startRecording">开始录音</button>
        <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
        <button @click="playRecording" :disabled="!recording">播放录音</button> -->


                <el-button type="primary" :icon="Share" circle @click="sharescreen()"/>
            </div>
        </div>

        <div>


    <h2 class="service-item-title">产品体验-实时语音翻译</h2>
        <div class="service-item-content service-item-taste-content">
          <div class="taste-content">
            <button class="taste-button ready-button" id="taste_button">开始转写</button>
          </div>
          <div class="start-taste">
            <div class="start-taste-left">
              <div class="time-box">
                <span class="start-taste-line">
                  <hr class="hr hr1">
                  <hr class="hr hr2">
                  <hr class="hr hr3">
                  <hr class="hr hr4">
                  <hr class="hr hr5">
                  <hr class="hr hr6">
                  <hr class="hr hr7">
                  <hr class="hr hr8">
                  <hr class="hr hr9">
                  <hr class="hr hr10">
                </span>
                <span class="total-time"><span class="used-time">00: 00</span></span>
              </div>
              <div class="start-taste-button">
                <button class="taste-button start-button">结束转写</button>
              </div>
            </div>
            <div class="output-box" id="result_output"></div>
          </div>
        </div>

        </div>

      </div>
    </div>
    </template>

    <script setup>
    import {
      Link,
      Delete,
      Edit,
      Message,
      Plus,
      Share,
    } from '@element-plus/icons-vue'
    import { reactive,ref,onMounted} from 'vue'
    import { isMyCourse } from '../api/course'
    import { useRoute,useRouter } from 'vue-router'
    import { useStaffStore } from '../stores/staff'
    import { getMyLessionFileList } from '../api/lessionfile'
    import { Base64 } from 'js-base64'
    import Board from "../components/Board.vue"
    import CanvaBoard from "../components/CanvaBoard.vue"

    // import { hmacsha256 } from 'public/js/hmac-sha256.js'
    // import { HmacSHA1 } from 'public/js/HmacSHA1.js'
    // import { md5 } from 'public/js/md5.js'
    // import { encbase64min } from 'public/js/enc-base64-min.js'
    // import { jquery } from 'public/js/jquery.js'
// import { index } from 'public/js/transindex.js_bak'

    const activeName = ref('first')

    const handleClick = (tab, event) => {
      console.log(tab, event)
    }

    const staffStore = useStaffStore()
    const username = staffStore.username;

    const route = useRoute()
    const currentRoute = useRouter()
    const courseid = route.query.courseid
    const lessionid = route.query.lessionid

    const TYPE_COMMAND_ROOM_ENTER = "enterRoom";
    const TYPE_COMMAND_ROOM_LIST = "roomList";
    const TYPE_COMMAND_DIALOGUE = "dialogue";
    const TYPE_COMMAND_READY = "ready";
    const TYPE_COMMAND_OFFER = "offer";
    const TYPE_COMMAND_ANSWER = "answer";
    const TYPE_COMMAND_CANDIDATE = "candidate";


    let iceServers={
        "iceServers":[
            {"url":"stun:stun.services.mozilla.com"},
            {"url":"stun:stun.l.google.com:19302"}
        ]
    };

    const offerOptions = {
        iceRestart: true,
        offerToReceiveAudio: false, //true,由于没有麦克风，所有如果请求音频，会报错，不过不会影响视频流播放
        offerToReceiveVideo: true
    };

    let websocket;
    let localMediaStream;
    let videoStream;
    let rtcPeerConnection;

    const lessiondata = reactive({
        list:[],
        isMyCourse:false,
        urlSrc:''
    })
    //lessionfile列表
    const lessionfiledata = reactive({
        list:[]
    })

    onMounted(() => {
      loaddata();
      //initAudio();
      //initwebsocket();
    })

    // function startSpeechRecognition() {
    //     window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition
    //       if(!window.SpeechRecognition){
    //         return
    //       }
    //       const recognition = new SpeechRecognition();
    //       recognition.onresult = function(event) {
    //           alert("0000000000000000000");
    //         const speechInput = document.getElementById('speechInput');
    //         alert("111111111111111111");
    //         speechInput.value = event.results[0][0].transcript;
    //         alert("222222222222222222222");
    //       };
    //       recognition.start();
    //       alert("tttttt");
    //     }


    //const isRecording = ref(false);
    //const recording = ref(null);
    // let mediaRecorder;

    //   navigator.mediaDevices.getUserMedia({ audio: true })
    //         .then(stream => {

    //           var mediaRecorder = new MediaRecorder(stream);


    //                 mediaRecorder.ondataavailable = function(event) {

    //                 };

    //                 mediaRecorder.start();


    //         })
    //         .catch(error => {
    //           console.log('无法访问麦克风：');
    //         });


    // const startRecording = async () => {





    //   const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    //   mediaRecorder = new MediaRecorder(stream);

    //   let audioChunks = [];

    //   mediaRecorder.addEventListener('dataavailable', event => {
    //     if (event.data.size > 0) {
    //        alert("111111111111111111111");
    //       audioChunks.push(event.data);
    //     }
    //   });

    //   mediaRecorder.addEventListener('stop', () => {
    //       alert("2222222222222222222222");
    //     const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
    //     recording.value = URL.createObjectURL(audioBlob);
    //   });

    //   mediaRecorder.start();
    //   isRecording.value = true;
    // };

    // const stopRecording = () => {
    //   isRecording.value = false;
    //   mediaRecorder.stop();
    // };

    // const playRecording = () => {
    //   const audio = new Audio(recording.value);
    //   audio.play();
    // };

    //const transcript = ref('');
    //let recognition;
    // function initAudio()
    // {


    //   // 检查浏览器是否支持 Web Speech API
    //   //if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window)
    //   {
    //     const recognition = new webkitSpeechRecognition();
    //     recognition.lang = 'en';  // 设置识别语言
    //     //recognition.continuous = true;  // 是否连续识别
    //     //recognition.interimResults = true;  // 是否返回中间结果
    // alert("000000000000000000000000");
    //     // 识别结果事件
    //     recognition.onresult = (event) => {
    //         //alert("111111111111111111111111111");
    //       //transcript.value = '';  // 清空之前的文本
    //      // for (let i = 0; i < event.results.length; ++i) {
    //      //   transcript.value += event.results[i][0].transcript;  // 拼接识别结果
    //       //}
    //       alert(event.results[i][0].transcript);
    //     };

    //     // 识别错误事件
    //     recognition.onerror = (event) => {
    //        alert("22222222222222222222222222");
    //       console.error('识别出错:', event.error);
    //     };

    //     // 识别结束事件
    //     recognition.onend = () => {
    //      alert('识别结束');
    //     };

    //     recognition.start();
    //   }
    //   // else {
    //   //    alert("333333333333333333333333");
    //   //  console.error('当前浏览器不支持语音识别');
    //   //}
    // }
    function loaddata()
    {
      isMyCourse({"courseid":courseid}).then((res) => {
        if (res.code == 200)
        {
          lessiondata.isMyCourse = res.data;
        }
      })
      getMyLessionFileList({"lessionid":lessionid}).then((res) => {
        if (res.code == 200)
        {
          lessionfiledata.list = res.data;
          var baseurl = import.meta.env['VITE_APP_BASE_API']
          var proviewurl = import.meta.env['VITE_PROVIEW']
          var url = baseurl +"/"+lessionfiledata.list[0].filepath
          lessiondata.urlSrc = proviewurl +"/onlinePreview?url=" + encodeURIComponent(Base64.encode(url))
        }
      })
    }
    function reseturl(filepath)
    {
        var baseurl = import.meta.env['VITE_APP_BASE_API']
        var proviewurl = import.meta.env['VITE_PROVIEW']
        var url = baseurl + "/"+filepath
        lessiondata.urlSrc = proviewurl + "/onlinePreview?url=" + encodeURIComponent(Base64.encode(url))
    }
    const handleMessage = (event) => {
        let message = JSON.parse(event.data);
        switch (message.command) {
            case TYPE_COMMAND_ROOM_ENTER://进入房间，然后打开本地共享桌面流媒体
                // if (message.message === "joined") {
                //     roomId = message.roomId;
                //     openLocalMedia()
                //         .then(() => {
                //             websocket.send(JSON.stringify({command: TYPE_COMMAND_READY, userId: userId, roomId: roomId}));
                //         })
                //         .catch(() => {
                //         })
                // } else
                {
                    //caller = true;
                    openLocalMedia()
                        .then(() => {
                        })
                        .catch(() => {
                        });
                }
                break;
            case TYPE_COMMAND_ROOM_LIST:
                break;
            case TYPE_COMMAND_DIALOGUE:
                break;
            case TYPE_COMMAND_READY:
                // if (caller)
                {
                    //初始化一个webrtc端点
                    if (!rtcPeerConnection)
                    {
                      rtcPeerConnection = new RTCPeerConnection(iceServers);
                      //添加事件监听函数
                      rtcPeerConnection.onicecandidate = onIceCandidate;
                      rtcPeerConnection.ontrack = onTrack;
                    }

                    //addStream相关的方法，已过时
                    //rtcPeerConnection.addTrack(localMediaStream);
                    for( const track of localMediaStream.getTracks()){
                        rtcPeerConnection.addTrack(track, localMediaStream);
                    }
                    rtcPeerConnection.createOffer(offerOptions)
                        .then(
                            setLocalAndOffer
                        )
                        .catch(() => {
                            }
                        );
                }
                break;
            case TYPE_COMMAND_OFFER:
                // if (!caller)
                {
                    //初始化一个webrtc端点
                    if (!rtcPeerConnection)
                    {
                      rtcPeerConnection = new RTCPeerConnection(iceServers);
                      //添加事件监听函数
                      rtcPeerConnection.onicecandidate = onIceCandidate;

                      rtcPeerConnection.ontrack = onTrack;
                    }

                    //rtcPeerConnection.addTrack(localMediaStream);
                    for (const track of localMediaStream.getTracks()) {
                        rtcPeerConnection.addTrack(track, localMediaStream);
                    }
                    //原因：后端接口返回的数据换行采用了\r\n方式，使得json文本无法解析带换行符的内容
                    //解决方法：将Json字符串中所有的\r\n转成\\r\\n
                    let sdpMessage = message.message;
                    sdpMessage.replace(/[\r]/g, "\\r").replace(/[\n]/g, "\\n");
                    console.log(sdpMessage);
                    let sdp = JSON.parse(sdpMessage).sdp;
                    rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp))
                        .then(
                        );
                    rtcPeerConnection.createAnswer(offerOptions)
                        .then(
                            setLocalAndAnswer
                        )
                        .catch(() => {
                            }
                        );
                }
                break;
            case TYPE_COMMAND_ANSWER:
                //原因：后端接口返回的数据换行采用了\r\n方式，使得json文本无法解析带换行符的内容
                //解决方法：将Json字符串中所有的\r\n转成\\r\\n
                let sdpMessage = message.message;
                sdpMessage.replace(/[\r]/g, "\\r").replace(/[\n]/g, "\\n");
                console.log(sdpMessage);
                let sdp = JSON.parse(sdpMessage).sdp;
                rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp))
                    .then(
                        //log("setRemoteDescription 完毕")
                    );
                break;
            case TYPE_COMMAND_CANDIDATE:
                let candidateMessage = message.message;
                console.log(candidateMessage);
                let candidate = JSON.parse(candidateMessage).candidate;
                let rtcIceCandidate = new RTCIceCandidate({
                    sdpMid: candidate.sdpMid,
                    sdpMLineIndex: candidate.label,
                    candidate: candidate.candidate
                });
                rtcPeerConnection.addIceCandidate(rtcIceCandidate)
                    .then(
                        log("addIceCandidate 完毕")
                        );
                break;
        }
    };


    const openLocalMedia = async () => {
        videoStream = await navigator.mediaDevices.getDisplayMedia({
            video: {MediaSource: "screen"},audio:false
        });
        const audioStream = await navigator.mediaDevices.getUserMedia({
            video:false,
            audio: {
                sampleSize: 100,
                frameRate: { max: 30 },
                noiseSuppression: true,
                echoCancellation: true,
                channelCount: 2
            }
        });
        videoStream.getVideoTracks()[0].onended = ()=>{
              leave();
        };
        var audioTrack = audioStream.getAudioTracks()[0];
        videoStream.addTrack(audioTrack);


        // recorder.onstop = (e) => {
        //     const completeBlob = new Blob(chunks, { type: "video/mp4" });
        //     videoFile = new File([completeBlob], "recording.mp4");
        //     console.log(videoFile);

        //     console.log(completeBlob);
        //     vimeoCall(videoFile);
        // };

        localMediaStream = videoStream;
        //测试添加到localVideo查看分享效果
        let localVideo = document.getElementById("localVideo");
        localVideo.srcObject = localMediaStream;
        localVideo.play();

    }

    //打开本地音视频,用promise这样在打开视频成功后，再进行下一步操作
    // async function openLocalMedia2() {
    //     ideoStream = await navigator.mediaDevices.getDisplayMedia({
    //         video: {MediaSource: "screen"},
    //     });
    //     audioStream = await navigator.mediaDevices.getUserMedia({
    //         audio: {
    //             sampleSize: 100,
    //             frameRate: { max: 30 },
    //             noiseSuppression: true,
    //             echoCancellation: true,
    //             channelCount: 2
    //         }
    //     });
    //     var audioTrack = audioStream.getAudioTracks()[0];
    //     videoStream.addTrack(audioTrack);

    //     localMediaStream = videoStream;
    //     let localVideo = document.getElementById("localVideo");
    //     localVideo.srcObject = localMediaStream;
    //     localVideo.play();
    // }
    function leave()
    {
       websocket.close();
    }
    function initwebsocket()
    {

    }

    //发起共享屏幕的指令
    function sharescreen()
    {
        //连接到课程lession的直播websocket
        if (!websocket) {
            websocket = new WebSocket("ws://192.168.0.103:8080/websocket");
        }
        websocket.onopen = () => {
            //连接到课程lession的直播websocket
            websocket.send(JSON.stringify({command:TYPE_COMMAND_ROOM_ENTER,username:username,roomId : lessionid}));
        };
        websocket.onclose = () => {

            videoStream.getTracks().forEach(track => {
                track.stop();
            });
            websocket = '';
            videoStream = '';
            localMediaStream = '';
        };
        websocket.onerror = () => {
        };
        websocket.onmessage = handleMessage;
    }

    const setLocalAndOffer = (sessionDescription) => {
        rtcPeerConnection.setLocalDescription(sessionDescription)
            .then(
                //log("setLocalDescription 完毕")
            );
        websocket.send(
            JSON.stringify({
                command: TYPE_COMMAND_OFFER,
                username:username,
                roomId: lessionid,
                message: {
                    sdp: sessionDescription,
                }
            })
        );
    };

    const setLocalAndAnswer = (sessionDescription) => {
        rtcPeerConnection.setLocalDescription(sessionDescription)
            .then(
               // log("setLocalDescription 完毕")
            );
        websocket.send(
            JSON.stringify({
                command: TYPE_COMMAND_ANSWER,
                username:username,
                roomId: lessionid,
                message: {
                    sdp: sessionDescription,
                }
            })
        );
    };

    const onTrack = (event) =>{
        // let remoteMediaStream = event.streams[0];
        // let remoteVideo = document.getElementById("remoteVideo");
        // remoteVideo.srcObject = remoteMediaStream;
        // remoteVideo.play();

    };

    const onIceCandidate = (event) =>{
        if (event.candidate) {
            //log("sending ice candidate");
            websocket.send(JSON.stringify({
                command: TYPE_COMMAND_CANDIDATE,
                username:username,
                roomId: lessionid,
                message: {
                    candidate:{
                        sdpMid: event.candidate.sdpMid,
                        sdpMLineIndex: event.candidate.sdpMLineIndex,
                        candidate: event.candidate.candidate
                    }
                }
            }));

        }
    };

    </script>

    <style lang="less" scoped>
    .con {
      display: flex; /* 启用Flexbox布局 */
      height: 100vh;
    }

    .left {
      flex: 2; /* 左边div占据剩余空间的1/3 */
    //   background-color: lightblue;
      padding: 10px;
      border-right: 1px solid #000000;
    }

    .right {
      flex: 1; /* 右边div占据剩余空间的2/3 */
      background-color: lightgrey;
      padding: 10px;
    }


    .content-panel {
      display: flex;
      align-items: center; /* 垂直居中 */
      justify-content: space-between; /* 左右内容对齐 */
      width: 100%; /* 根据需要调整宽度 */
      padding-top: 10px; /* 根据需要调整内边距 */
    }

    .content {
      /* 内容样式 */
      margin-left: 5px;;
    }

    .button {
      /* 按钮样式 */
      margin-right: 5px;
    }
    .demo-tabs > .el-tabs__content {
      padding: 32px;
      color: #6b778c;
      font-size: 32px;
      font-weight: 600;
    }

    </style>
